package api

import (
	"net/http"
	"go-web/model"
	"encoding/json"
	"io/ioutil"
	"strconv"
	"go-web/web"
)


func UserHandle() web.WebHandler {
	return func(writer http.ResponseWriter, request *http.Request) {
		writer.Header().Set("Content-Type", "application/json")
		request.ParseForm()
		method := request.Method

		rps,_ := json.Marshal(ERROR)

		if method == POST {
			idstr := request.Form.Get("id")

			body,err := ioutil.ReadAll(request.Body)
			if err != nil {
				writer.Write(rps)
				return
			}
			var user model.User
			err = json.Unmarshal(body, &user)
			if err != nil {
				writer.Write(rps)
				return
			}

			if idstr != "" {
				id,err := strconv.Atoi(idstr)
				if err != nil {
					writer.Write(rps)
					return
				}
				user.Id = id

				_,err = user.Update()
				if err != nil {
					writer.Write(rps)
					return
				}
			} else  {
				_,err := user.Save()
				if err != nil {
					writer.Write(rps)
					return
				}
			}

			datas := make(map[string]int)
			datas["id"] = user.Id

			data,err := json.Marshal(datas)
			if err != nil {
				writer.Write(rps)
				return
			}
			writer.Write(data)

		} else if method == GET {
			idstr := request.Form.Get("id")
			if "" == idstr {
				writer.Write(rps)
				return
			}
			id,err := strconv.Atoi(idstr)
			if err != nil {
				writer.Write(rps)
				return
			}
			user := &model.User{Id:id}
			u := user.GetById()
			if u == nil {
				writer.Write(rps)
				return
			}
			data,err := json.Marshal(u)
			if err != nil {
				writer.Write(rps)
				return
			}
			writer.Write(data)
		} else if method == DELETE {
			idstr := request.Form.Get("id")
			if idstr == "" {
				writer.Write(rps)
				return
			}
			id,err := strconv.Atoi(idstr)
			if err != nil {
				writer.Write(rps)
				return
			}
			user := &model.User{Id:id}
			_,err = user.Delete()
			if err != nil {
				writer.Write(rps)
				return
			}
			data,err := json.Marshal(SUCCESS)
			if err != nil {
				writer.Write(rps)
				return
			}
			writer.Write(data)
		}
	}
}